import * as WeChat from 'react-native-wechat-with-miniprogram-share'
import RNIap from 'react-native-iap'
import { iosPayValidate } from './RequestAPI'
import { WXAPPID, MINIID as miniUserName } from 'src/config/index'
WeChat.registerApp(WXAPPID)

export function shareToSession ({
  savePath,
  title = '人之初分享',
  description = '人之初分享',
  mediaTagName = '人之初分享'
}) {
  // 微信应用注册
  return new Promise((resolve, reject) => {
    WeChat.isWXAppInstalled().then(isInstalled => {
      if (isInstalled) {
        WeChat.shareToSession({
          type: 'imageFile',
          title,
          description,
          mediaTagName,
          messageAction: undefined,
          messageExt: undefined,
          imageUrl: 'file://' + savePath // require the prefix on both iOS and Android platform
        })
          .then(wxShareResult => {
            if (wxShareResult.errCode === 0) {
              resolve('分享成功')
            } else {
              reject('分享失败')
            }
          })
          .catch(() => {
            reject('分享失败')
          })
      } else {
        reject('未安装微信')
      }
    })
  })
}
export function shareToTimeline ({
  savePath,
  title = '人之初分享',
  description = '人之初分享',
  mediaTagName = '人之初分享'
}) {
  // 微信应用注册
  return new Promise((resolve, reject) => {
    WeChat.isWXAppInstalled().then(isInstalled => {
      if (isInstalled) {
        WeChat.shareToTimeline({
          type: 'imageFile',
          title,
          description,
          mediaTagName,
          messageAction: undefined,
          messageExt: undefined,
          imageUrl: 'file://' + savePath // require the prefix on both iOS and Android platform
        })
          .then(wxShareResult => {
            if (wxShareResult.errCode === 0) {
              resolve('分享成功')
            } else {
              reject('分享失败')
            }
          })
          .catch(() => {
            reject('分享失败')
          })
      } else {
        reject('未安装微信')
      }
    })
  })
}
export function shareToWXMiniProgram ({
  title = '大学生兼职',
  shareUrl = 'pages/job-detail/index',
  thumb = 'http://image.static.renzhichu.cn/assets/logo.jpg'
}) {
  // 微信应用注册
  return new Promise((resolve, reject) => {
    WeChat.isWXAppInstalled().then(isInstalled => {
      if (isInstalled) {
        WeChat.shareToWXMiniProgram({ title, thumb, shareUrl, miniUserName })
          .then(wxShareResult => {
            if (wxShareResult.errCode === 0) {
              resolve('分享成功')
            } else {
              reject('分享失败')
            }
          })
          .catch(() => {
            reject('分享失败')
          })
      } else {
        reject('未安装微信')
      }
    })
  })
}
export function WXPay ({
  partnerid: partnerId,
  prepayid: prepayId,
  noncestr: nonceStr,
  timestamp: timeStamp,
  package: _package,
  sign
}) {
  return new Promise((resolve, reject) => {
    WeChat.isWXAppInstalled()
      .then(isInstalled => {
        console.info(
          'wxpay',
          isInstalled,
          partnerId, // 商家向财付通申请的商家id
          prepayId, // 预支付订单
          nonceStr, // 随机串，防重发
          timeStamp, // 时间戳，防重发
          _package, // 商家根据财付通文档填写的数据和签名
          sign
        ) // 商
        if (isInstalled) {
          return WeChat.pay({
            partnerId, // 商家向财付通申请的商家id
            prepayId, // 预支付订单
            nonceStr, // 随机串，防重发
            timeStamp, // 时间戳，防重发
            package: _package, // 商家根据财付通文档填写的数据和签名
            sign // 商家根据微信开放平台文档对数据做的签名
          })
        } else {
          reject('未安装微信')
        }
      })
      .then(({ errCode, errStr }) => {
        console.log('wxpay', errCode, errStr)
        if (!errCode) {
          resolve()
        } else {
          reject('支付失败')
        }
      })
      .catch(e => {
        console.info('支付失败', e)
        reject('支付失败')
      })
  })
}

export function IAPPay ({
  iapId,
  recordId,
  postId,
  businessType,
  companyId,
  userId
}) {
  // debugger
  return new Promise((resolve, reject) => {
    RNIap.getProducts([iapId])
      .then(res => {
        return RNIap.requestPurchase(iapId, true)
      })
      .then((res = {}) => {
        console.log(res)
        const { transactionReceipt: payload, transactionId } = res
        const params = {
          payload,
          transactionId,
          recordId,
          businessType
        }
        if (postId) {
          params['postId'] = postId
        }
        const headers = { companyId, userId }
        return iosPayValidate({ params, headers })
      })
      .then(res => {
        resolve()
      })
      .catch(error => {
        console.log(error)
        reject('支付失败')
      })
  })
}

export const IAPRestore = () => {
  return RNIap.getAvailablePurchases()
}
export const IAPProductsDetail = productIds => {
  return RNIap.getProducts(productIds)
}
